package com.fucking.great.servlert;

import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public abstract class ServletUtil extends cn.hutool.extra.servlet.ServletUtil {
    public JSONObject jsonObject;
    static final ThreadLocal<ServletRequest> REQUEST = new ThreadLocal<>();
    static final ThreadLocal<ServletResponse> RESPONSE = new ThreadLocal<>();
    public static void set(ServletRequest request, ServletResponse response){
        REQUEST.set(request);
        RESPONSE.set(response);
    }
    public static ServletRequest getServletRequest(){
        return REQUEST.get();
    }
    public static ServletResponse getServletResponse(){
        return RESPONSE.get();
    }
    public static void warpper(){
        try {
            HttpServletRequest servletRequest = (HttpServletRequest) getServletRequest();
            RequestWrapper value = new RequestWrapper(servletRequest);
                    // IocUtil.getBean("RequestWrapper",RequestWrapper.class,servletRequest);
            REQUEST.set(value);
        } catch (Exception e) {
           throw new UtilException(e);
        }
    }
    public static void removue(){
        REQUEST.remove();
        RESPONSE.remove();
    }

    /**
     * request.getServletPath()返回为空的问题
     * https://www.ktanx.com/blog/p/3551
     * @param request
     * @return 获得ServletPath路径.
     */
    public static String getServletPath(HttpServletRequest request){
        String servletPath = request.getServletPath();
        String pathInfo = request.getPathInfo();
        if (StrUtil.length(pathInfo) > 0) {
            servletPath = servletPath + pathInfo;
        }
        return servletPath;
    }
}
